1T_정규 표현식 ( Regular Expression ) - 이메일, 핸드폰 번호

이메일, 핸드폰 번호 정규표현식

In [1]:
with open("crawled.txt", "r", encoding='utf8') as f:   #crawled.txt는 보기와 같이 임의로 텍스트 파일을 만들었습니다.
    data = f.read()
    print(data)


중국 중앙은행인 인민은행은 16일 환율을 달러당 6.6305위안으로 고시했다. 지난 15일 고시환율 달러당kimkipoy@naver.com 6.6430위안에 비해 달러 대비 위안 가치가 0.19% 상승했다.
A new material has been created that 공일공육이삼오삼삼일칠can self-assemble into a swarm, acting as a single-minded unit.

The material, which is made up of a set up spheres, is able공일공-둘둘삼삼-사사오오 to automatically arrange into a pattern when exposed to an electric field.

In the future, this could be used to create armies of robots that act as a relentle010-4567-9201ss, single-minded unit.
한경닷컴 증권금융팀

In [2]:
import re

with open("crawled.txt", "r", encoding='utf8') as f:
    data = f.read()
    
    phonenumber_regex = "010"                             # 1. 정규표현식 (regex)
# phonenumber_regex = "\d{3}[-]?\d{4}[-]?\d{4}"
    # \d => 숫자가 나온다. => [0-9]
    # \d{3} => 숫자가 3번 나온다.
    # [-]? => "-"가 나올 수도 있고 안 나올 수도 있다.
    phonenumber_pattern = re.compile(phonenumber_regex)   # 파이썬에서 정규표현식을 사용할 수 있도록 SRE_Pattern 객체로 변경
    phonenumber_list = phonenumber_pattern.findall(data)  # 2. 파이썬에서 정규표현식 함수를 사용한다.

print(phonenumber_list)


['010']

In [3]:
with open("crawled.txt", "r", encoding='utf8') as f:
    data = f.read()
        
    phonenumber_regex = "[0-9영공빵일이둘삼사오육칠팔구]{3}[-]?[0-9영공빵일이둘삼사오육칠팔구]{3,4}[-]?[0-9영공빵일이둘삼사오육칠팔구]{4}" 
    # * => 0~n
    # ? => 0-1
    # + => 1-n
    
    # 이런 데이터를 먼저 전처리를 하고 ( 공 => 0 )( 지금은 이게 더 바람직 )
    
    phonenumber_pattern = re.compile(phonenumber_regex)  
    phonenumber_list = phonenumber_pattern.findall(data)
    
    # email_regex = "[a-zA-Z0-9_]+[@][a-zA-Z0-9_]+[.][a-z]+[.]?[a-z]+$"
    email_regex = "[a-zA-Z0-9_]+[@][a-zA-Z0-9.]+"
    # email_regex = ""
    # 정규표현식
    
    # "다섯" 이라는 텍스트가 포함이 되는...
    # "12다섯456"
    # [a-zA-Z0-9_]*다섯[a-zA-Z0-9_]*
    
    # {} -> 자릿수가 정해저있는 상황 ( 핸드폰 번호 ... )
    email_pattern = re.compile(email_regex)
    email_list = email_pattern.findall(data)
    
    # .com
    # .co.kr
    
print(phonenumber_list)
print(email_list)


['공일공육이삼오삼삼일칠', '공일공-둘둘삼삼-사사오오', '010-4567-9201']
['kimkipoy@naver.com']

In [4]:
def preprocess(phonenumber):
    preprocess_dict = {
        "영": 0,
        "공": 0,
        "일": 1,
        "둘": 2,
        "이": 2,
        "삼": 3,
        "사": 4,
        "오": 5,
        "육": 6,
        "칠": 7,
        "팔": 8,
        "구": 9,
        "-": "",
    }
    
    for key, value in preprocess_dict.items():
        phonenumber = phonenumber.replace(key, str(value))
    return phonenumber

In [5]:
[preprocess(phonenumber) for phonenumber in phonenumber_list]


Out[5]:
['01062353317', '01022334455', '01045679201']

3T_객체 지향 프로그래밍 - 클래스 메쏘드와 인스턴스 메쏘드

  • Class - 클래스는 매우 중요합니다.
  • Class => object ( 객체가 생성되는 클래스 ) 에 대해서만 배웠다.
예제: 피보나치 수열

In [6]:
class Fibonacci():
    
    cache = {1: 0, 2: 1}
    # n=1 => 0
    # n=2 => 1
    # f(n) = f(n-1) + f(n-2)
    
#     def __init__(self):
#         self.cache = {}
# 기존의 이런 형태가 아니라 다른 형태로 받기 위해서

    # 클래스 => 클래스 메쏘드
    # 객체 ( 인스턴스 ) => 인스턴스 메쏘드

    @staticmethod  # 클래스 메쏘드 
    def calc(n):  # self 가 없습니다. self.cache가 아니라 Fibonacci.cache로 바뀜
        
        if n in Fibonacci.cache:   
            return Fibonacci.cache[n]
        
        if n <= 0:
            return 0
        
#         if n == 1:
#             Fibonacci.cache[n] = 0
#             return Fibonacci.cache[n]
        
#         if n == 2:
#             Fibonacci.cache[n] = 1
#             return Fibonacci.cache[n]
        
        Fibonacci.cache[n] = Fibonacci.calc(n-1) + Fibonacci.calc(n-2)
        return Fibonacci.cache[n]

In [7]:
Fibonacci.calc(20)


Out[7]:
4181

In [8]:
Fibonacci.cache


Out[8]:
{1: 0,
 2: 1,
 3: 1,
 4: 2,
 5: 3,
 6: 5,
 7: 8,
 8: 13,
 9: 21,
 10: 34,
 11: 55,
 12: 89,
 13: 144,
 14: 233,
 15: 377,
 16: 610,
 17: 987,
 18: 1597,
 19: 2584,
 20: 4181}
예제: Factorial

In [9]:
class Factorial():
    
    cache = {
        1: 1,
    }
    
    @staticmethod
    def run(n):
        
        if n in Factorial.cache:
            return Factorial.cache[n]
        
        Factorial.cache[n] = n * Factorial.run(n-1)
        return Factorial.cache[n]
    
    @staticmethod
    def prettify():
        print("\n".join([
            "{n}! == {result}".format(n=key, result=value)
            for key, value
            in Factorial.cache.items()
        ]))

In [10]:
Factorial.run(4)


Out[10]:
24

In [11]:
Factorial.prettify()


1! == 1
2! == 2
3! == 6
4! == 24
예제: 달력

In [12]:
import functools


class Calendar():
    
    __days = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31,
    }
    
    @staticmethod
    def is_leap(year):
        return\
            year % 4 == 0\
            and not year % 100 == 0\
            or year % 400 == 0
        
    @staticmethod
    def days_in(year):
        days = Calendar.__days.copy()
        
        # days 라는 새로운 변수 => Calendar.__days 를 가리키고 있는 애 
        # 우리가 의도한 바 : 기존의 애를 복사하는 것
        
        days[2] += int(Calendar.is_leap(year))  # True => 1, 
                                                # False => 0
        return days
    
    @staticmethod
    def total_days_in(year):
        return functools.reduce(
            lambda x,y: x+y,
            Calendar.days_in(year).values(),
        )
        
    
    @staticmethod
    def total_days_until(year):
#         total_days = 0
#         for i in range(1900, year):
#             total_days += Calendar.total_days_in(i)
#         return total_days
        return functools.reduce(
            lambda x,y: x+y,
            [
                Calendar.total_days_in(i)
                for i
                in range(1900, year)  
            ]
        )
        
        
    # 1년 1월 1일 부터 특정 년도 까지의 day 수 합계를 구하시오.
    # 예, 1년 1월 1일 부터 2년 1월 1일 => 365
    #     1년 1월 1일 부터 3년 1월 1일 => 365 * 2
    # 하는 이유: day 수 합계 % 7 ==> 요일 ( 1년 1월 1일이 월요일 입니다 )

In [13]:
Calendar.total_days_until(1905)


Out[13]:
1826

In [14]:
Calendar.days_in(2016)


Out[14]:
{1: 31,
 2: 29,
 3: 31,
 4: 30,
 5: 31,
 6: 30,
 7: 31,
 8: 31,
 9: 30,
 10: 31,
 11: 30,
 12: 31}